package com.config;

import com.generator.entity.Route;
import com.generator.mapper.RouteMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.concurrent.Semaphore;

/**
 * @Author: htj
 * @Date: 2021/10/5 0005 上午 0:18
 */
@Service
public class TimedTask {

    @Autowired
    private RouteMapper routeMapper;

    //引用全局唯一的存储并发数的map
    @Autowired
    private HashMap<Integer, Semaphore> apiConcurrentMap;

    //引用全局唯一的存储超时时间的map
    @Autowired
    private HashMap<Integer, Integer> apiOvertimeMap;

    //引用全局唯一的存储开关的map
    @Autowired
    private HashMap<Integer, Integer> apiSwitchMap;

    @Scheduled(cron = "* * * * * 1-7")
    public void update() {

        List<Route> routeList = routeMapper.selectList(null);
        System.out.println("**************这一秒执行了定时任务");

        //更新最大并发数
        for (int i = 0; i < routeList.size(); i++) {
            Semaphore semaphore = new Semaphore(routeList.get(i).getConcurrent());
            apiConcurrentMap.put(routeList.get(i).getId(), semaphore);
        }

        //更新超时时间
        for (int i = 0; i < routeList.size(); i++) {
            int overtime = routeList.get(i).getOvertime();
            apiOvertimeMap.put(routeList.get(i).getId(), overtime);
        }

        //更新开关
        for (int i = 0; i < routeList.size(); i++) {
            int availble = routeList.get(i).getAvailable();
            apiSwitchMap.put(routeList.get(i).getId(), availble);
        }
    }

}
